package shj.blackberry.i.ui;

import net.rim.device.api.system.KeyListener;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.TextField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import shj.blackberry.i.util.FileAccess;
import shj.blackberry.i.util.GuaAttribute;
import shj.blackberry.i.util.GuaXiang;

/**
 * 界面类
 * @author shan.hongjie
 *
 */
final class UserInterfaceScreen extends MainScreen {
	
	HorizontalFieldManager _fieldManagerInput;//卦象输入
	HorizontalFieldManager _fieldManagerCommand;//命令
	VerticalFieldManager _fieldManagerContent;//卦辞、爻辞等
	
	BasicEditField _input;
	
	//标题，显示待分析卦
	LabelField title;

	TextField rtfGuaci;

	
	/**
	 * 卦象01字符序列，比如011010110110
	 * 第i,i+1(i为奇)的4种组合11,10,01,00分别代表太阳，少阳，少阴，太阴
	 */
	String strGuaImage="";
	GuaXiang  guaXiang;//卦对象
	boolean hasGenGua = false;//是否已经生成卦
	int displayed = 0;

	public UserInterfaceScreen() {
		super();

		this.setVirtualExtent(5, 5);
		
		title = new LabelField("易",LabelField.HCENTER | LabelField.USE_ALL_WIDTH);
		setTitle(title);	//设定程序标题
		
		
		
		_fieldManagerInput = new HorizontalFieldManager();
		_fieldManagerCommand = new HorizontalFieldManager();
		_fieldManagerContent = new VerticalFieldManager();
		//将各元素加载至MainScreen
		add(_fieldManagerInput);
		add(new SeparatorField());
		add(_fieldManagerCommand);
		add(new SeparatorField());
		add(_fieldManagerContent);
		
		strGuaImage = "";
		
		_input = new BasicEditField("输入卦象:", strGuaImage);
		_fieldManagerInput.add(_input);//添加卦象输入区


		
		//将按钮们放入命令区
		ButtonField autoGenButton = new ButtonField("自");
		ButtonField benButton = new ButtonField("本w");
		ButtonField huButton = new ButtonField("互e");
		ButtonField zhiButton = new ButtonField("之r");
		ButtonField cuoButton = new ButtonField("错t");
		ButtonField zongButton = new ButtonField("综y");
		ButtonField resetButton = new ButtonField("重u");
		_fieldManagerCommand.add(autoGenButton);
		_fieldManagerCommand.add(benButton);
		_fieldManagerCommand.add(huButton);
		_fieldManagerCommand.add(zhiButton);
		_fieldManagerCommand.add(cuoButton);
		_fieldManagerCommand.add(zongButton);
		_fieldManagerCommand.add(resetButton);
		
		//卦辞显示栏
		rtfGuaci = new TextField(TextField.NO_EDIT_MODE_INPUT);
		rtfGuaci.setEditable(false);
		_fieldManagerContent.add(rtfGuaci);
		
		
		
		FieldChangeListener listenerAutoGen = new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				UserInterfaceScreen.this.reset();
				_input.setText(GuaXiang.getRandomStringImage());
				if(dealBeforeQuery())
				{
					UserInterfaceScreen.this.rtfGuaci.setText("已自动生成卦象:-)");
				}else{
					UserInterfaceScreen.this.rtfGuaci.setText("生成卦象失败:-(");
				}
			}
		};
		autoGenButton.setChangeListener(listenerAutoGen);
		
		FieldChangeListener listenerBen = new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				if(dealBeforeQuery()){
					UserInterfaceScreen.this.setTitle("本卦："+guaXiang.getBenGua());
//					UserInterfaceScreen.this.doPaint();
					UserInterfaceScreen.this.rtfGuaci.setText(guaXiang.getBenGuaCi());
					UserInterfaceScreen.this.rtfGuaci.setFocus();
					UserInterfaceScreen.this.rtfGuaci.setCursorPosition(BOTTOMMOST);
		
				}
			}
		};
		benButton.setChangeListener(listenerBen);
		
		FieldChangeListener listenerHu = new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				if(dealBeforeQuery()){
					UserInterfaceScreen.this.setTitle("互卦："+guaXiang.getHuGua());
					UserInterfaceScreen.this.rtfGuaci.setText(guaXiang.getHuGuaCi());
					UserInterfaceScreen.this.rtfGuaci.setFocus();
					UserInterfaceScreen.this.rtfGuaci.setCursorPosition(BOTTOMMOST);
				}
			}
		};
		huButton.setChangeListener(listenerHu);
		
		FieldChangeListener listenerZhi = new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				if(dealBeforeQuery()){
					UserInterfaceScreen.this.setTitle("之卦："+guaXiang.getZhiGua());
					UserInterfaceScreen.this.rtfGuaci.setText(guaXiang.getZhiGuaCi());
					UserInterfaceScreen.this.rtfGuaci.setFocus();
					UserInterfaceScreen.this.rtfGuaci.setCursorPosition(BOTTOMMOST);
				}
			}
		};
		zhiButton.setChangeListener(listenerZhi);
		
		FieldChangeListener listenerCuo = new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				if(dealBeforeQuery()){
					UserInterfaceScreen.this.setTitle("错卦："+guaXiang.getCuoGua());
					UserInterfaceScreen.this.rtfGuaci.setText(guaXiang.getCuoGuaCi());
					UserInterfaceScreen.this.rtfGuaci.setFocus();
					UserInterfaceScreen.this.rtfGuaci.setCursorPosition(BOTTOMMOST);
				}
			}
		};
		cuoButton.setChangeListener(listenerCuo);
		
		FieldChangeListener listenerZong = new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				if(dealBeforeQuery()){
					UserInterfaceScreen.this.setTitle("综卦："+guaXiang.getZongGua());
					UserInterfaceScreen.this.rtfGuaci.setText(guaXiang.getZongGuaCi());
					UserInterfaceScreen.this.rtfGuaci.setFocus();
					UserInterfaceScreen.this.rtfGuaci.setCursorPosition(BOTTOMMOST);
				}
			}
		};
		zongButton.setChangeListener(listenerZong);
		
		FieldChangeListener listenerReset = new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				UserInterfaceScreen.this.reset();
			}
		};
		resetButton.setChangeListener(listenerReset);
		
		KeyListener kla = new KeyListener(){
			//快捷键们
			public boolean keyChar(char key, int status, int time) {
				if(key=='q'||key=='Q'){
					UserInterfaceScreen.this.reset();
					_input.setText(GuaXiang.getRandomStringImage());
					if(dealBeforeQuery())
					{
						UserInterfaceScreen.this.rtfGuaci.setText("已自动生成卦象:-)");
					}else{
						UserInterfaceScreen.this.rtfGuaci.setText("生成卦象失败:-(");
					}
				
					return true;
				}else if(key=='w'||key=='W'){
						if(dealBeforeQuery()){
							UserInterfaceScreen.this.setTitle("本卦："+guaXiang.getBenGua());
							UserInterfaceScreen.this.rtfGuaci.setText(guaXiang.getBenGuaCi());
							UserInterfaceScreen.this.rtfGuaci.setFocus();
							UserInterfaceScreen.this.rtfGuaci.setCursorPosition(TOPMOST);
						}
					return true;
				}else if(key=='e'||key=='E'){
					if(dealBeforeQuery()){
						UserInterfaceScreen.this.setTitle("互卦："+guaXiang.getHuGua());
						UserInterfaceScreen.this.rtfGuaci.setText(guaXiang.getHuGuaCi());
						UserInterfaceScreen.this.rtfGuaci.setFocus();
						UserInterfaceScreen.this.rtfGuaci.setCursorPosition(TOPMOST);
					}
					return true;
				}else if(key=='r'||key=='R'){
					if(dealBeforeQuery()){
						UserInterfaceScreen.this.setTitle("之卦："+guaXiang.getZhiGua());
						UserInterfaceScreen.this.rtfGuaci.setText(guaXiang.getZhiGuaCi());
						UserInterfaceScreen.this.rtfGuaci.setFocus();
						UserInterfaceScreen.this.rtfGuaci.setCursorPosition(TOPMOST);
					}
					return true;
				}else if(key=='t'||key=='T'){
					if(dealBeforeQuery()){
						UserInterfaceScreen.this.setTitle("错卦："+guaXiang.getCuoGua());
						UserInterfaceScreen.this.rtfGuaci.setText(guaXiang.getCuoGuaCi());
						UserInterfaceScreen.this.rtfGuaci.setFocus();
						UserInterfaceScreen.this.rtfGuaci.setCursorPosition(TOPMOST);
					}
					return true;
				}else if(key=='y'||key=='Y'){
					if(dealBeforeQuery()){
						UserInterfaceScreen.this.setTitle("综卦："+guaXiang.getZongGua());
						UserInterfaceScreen.this.rtfGuaci.setText(guaXiang.getZongGuaCi());
						UserInterfaceScreen.this.rtfGuaci.setFocus();
						UserInterfaceScreen.this.rtfGuaci.setCursorPosition(TOPMOST);
					}
					return true;
				}else if(key=='u'||key=='U'){
					UserInterfaceScreen.this.reset();
					return true;
				}else if(key==' '){
					UserInterfaceScreen.this._input.setFocus();
				}
				return false;
			}

			public boolean keyDown(int keycode, int time) {
				return false;
			}
			public boolean keyRepeat(int keycode, int time) {
				return false;
			}
			public boolean keyStatus(int keycode, int time) {
				return false;
			}
			public boolean keyUp(int keycode, int time) {
				return false;
			}
		};
		this.addKeyListener(kla);
	}


	/**
	 * 重置卦对象
	 */
	private void reset(){
		strGuaImage="";
		hasGenGua=false;
		_input.setEditable(true);
		_input.setLabel("输入卦象:");
		_input.setText("");
		rtfGuaci.setText("已重置:-)");
		title = new LabelField("易",LabelField.HCENTER | LabelField.USE_ALL_WIDTH);
		_input.setFocus();
		this.setTitle(title);
	}
	
	/**
	 * 查询各卦象卦辞前的标识工作
	 * @return 已存在卦象或不存在而后成功生成则返回true，否则false
	 */
	private boolean dealBeforeQuery(){
		if(this.hasGenGua){
			return true;
		}else{
			try {
				strGuaImage = _input.getText();
				guaXiang = GuaXiang.GuaXiang(strGuaImage);
				this.hasGenGua = true;
				
				_input.setLabel("卦:");
				String benGuaCode = guaXiang.getBenGua();
				GuaAttribute ga = new GuaAttribute(benGuaCode);
				String benGuaName = ga.getGuaName();
				if(benGuaName.length()==1){
					benGuaName = "  "+benGuaName;
				}
				_input.setText(benGuaName+benGuaCode+" 爻:"+guaXiang.getYaoFlag()+" 宫:"+ga.getGong()+" 世:"+ga.getShiNumber());
				_input.setEditable(false);
				
				return true;
			} catch (Exception e) {
				Dialog.alert("请正确输入卦象的01序列");
				return false;
			}
		}
	}
	
	private MenuItem _about = new MenuItem("关于", 1, 1) {
		public void run() {
			showText("about");
		}
	};
	private MenuItem _help = new MenuItem("帮助", 2, 2) {
		public void run() {
			showText("help");
		}
	};
	private MenuItem _zsby = new MenuItem("增删卜易", 7, 7) {
		public void run() {
			showText("zsby");
		}
	};
	private MenuItem _others = new MenuItem("其他基础", 10, 10) {
		public void run() {
			showText("others");
		}
	};
	private MenuItem _close = new MenuItem("关闭", 11, 11) {
		public void run() {
			onClose();
		}
	};
	
	
	
	/**
	 * 根据文件名读取数据，并在新界面展示
	 * @param fileName 文件名（文件存放于程序数据文件夹）
	 */
	private void showText(String fileName){
		MainScreen showScreen = new MainScreen();
		//注意，若用LabelField当有大文本时会有outofmemory的错误
		TextField textField = new TextField(TextField.NO_EDIT_MODE_INPUT );
		String fileContent = FileAccess.getStringFromDataDirFile(fileName);
		textField.setText(fileContent);
		textField.setEditable(false);
		showScreen.add(textField);
		UserInterface.getUiApplication().pushScreen(showScreen);
	}

	protected void makeMenu(Menu menu, int instance) {
		menu.add(_about);//关于
		menu.add(_close);//关闭
		menu.add(_help);//帮助
		menu.add(_zsby);//增删卜易
		menu.add(_others);//其他基础
	}


	public boolean onClose() {
//		Dialog.alert("Goodbye!");
		System.exit(0);
		return true;
	}
}
